/**
 * Created by pzs on 2017/10/26.
 *
 * 精算-复核 业务功能模块的控制器
 */
var async = require('async');
var toolUtil = require('../common/utils/toolUtil');
var messageUtil = require('../common/utils/messageUtil');
var commission = require('../services/commissionService');
var moment = require('moment');

/*宝宝树四期 大使业绩统计的相关计算  pzs 20171031  start**/
exports.ambassadorPerformance = function(req, res){


    // 是否启用系统维护flag，
    // flag=1，启用，并且需要维护的一个时间段， 在该时间段内，用户不能访问；
    // flag = 2，不启用，用户可以一直访问 ；
    // flag = 3 , 直接启用，用户不能访问。
    var flag = global.commissionH5Flag;

    // flag从redis里取值
    var commissionH5FlagRedisKey = "h5:commission:commissionH5FlagRedisKey";
    redisClient.get(commissionH5FlagRedisKey, function (err, commissionH5FlagValue) {
        if (commissionH5FlagValue) {
            logger.debug("commissionH5FlagValue从redis中取得值..." + commissionH5FlagValue);
            flag = commissionH5FlagValue;
        } else {
            flag = global.commissionH5Flag;
            logger.debug("commissionH5Flag从配置文件中取得..." + commissionH5Flag);
        }

        var timeStart = global.commissionH5TimeStart;
        var timeEnd = global.commissionH5TimeEnd;
        var systemUpdateMsg = "系统更新中，请稍后查询";

        if(flag == 1){
            // flag=1，启用，并且需要维护的一个时间段， 在该时间段内，用户不能访问；
            var timeCurt = (new Date()).getTime();
            var today = moment(new Date()).format("YYYY-MM-DD");
            timeStart = today+" "+timeStart;
            timeEnd = today+" "+timeEnd;

            timeStart = moment(timeStart, "YYYY-MM-DD HH:mm:ss");
            timeEnd = moment(timeEnd, "YYYY-MM-DD HH:mm:ss");

            if(timeCurt>=timeStart && timeCurt<=timeEnd){
                res.json(messageUtil.composeFailedMessage(req, systemUpdateMsg, 3));
                return;
            }
        }
        else if(flag == 3) {
            // flag = 3 , 直接启用，用户不能访问。
            res.json(messageUtil.composeFailedMessage(req, systemUpdateMsg, 3));
            return;
        }
        else if(flag == 2){
            // flag = 2，不启用，用户可以一直访问 ；
        }

        // req.params.token = "3232";

        toolUtil.getUserByToken(req.params.token, function(error, result){


            if(!result){
                logger.debug("commission-controller.js--ambassadorPerformance():userId:"+req.params.token+"  msg:" + error.message)
                res.json(messageUtil.composeFailedMessage(req, "登录已过期，请重新登录", 0));
                return ;
            }

            var userId = result._id;
            // userId = "5994340ee09d55c408e875e9";
            // console.log("userId:"+userId);


            // 是否指定某些人可以访问
            var tempCommissionH5UserFlag = global.commissionH5UserFlag;

            var commissionH5UserFlagReidsKey = "h5:commission:commissionH5UserFlagReidsKey";
            redisClient.get(commissionH5UserFlagReidsKey, function (err, commissionH5UserFlagValue) {
                if (commissionH5UserFlagValue) {
                    logger.debug("commissionH5UserFlagValue..." + commissionH5UserFlagValue);
                    tempCommissionH5UserFlag = commissionH5UserFlagValue;
                } else {
                    tempCommissionH5UserFlag = global.commissionH5UserFlag;
                    logger.debug("commissionH5UserFlag从配置文件中取得..." + commissionH5UserFlag);
                }

                // 白名单用户
                var allowCommissionH5UserIds = "h5:commission:allowCommissionH5UserIdsReidsKey";
                redisClient.get(allowCommissionH5UserIds, function (err, allowCommissionH5UserIdsValue) {
                    // 允许部分人访问
                    if(tempCommissionH5UserFlag == 2) {
                        var userIdString = userId.toString();
                        if (allowCommissionH5UserIdsValue.indexOf(userIdString) == -1) {
                            logger.debug("当前用户不在允许访问名单中..." + tempCommissionH5UserFlag + " @ " + userIdString);
                            logger.debug(allowCommissionH5UserIdsValue);
                            // 如果没在允许列表中的话，则禁止访问
                            res.json(messageUtil.composeFailedMessage(req, systemUpdateMsg, 3));
                            return;
                        }
                    }

                    async.series({
                        close_actuarial: function (done) {
                            commission.getWaitCloseActuarial(userId, function(error, result){
                                done(null, result)
                            })
                        },
                        community_brokerage: function (done) {
                            commission.getMyCommunityBrokerage(userId, function(error, result){
                                done(null, result)
                            })
                        },
                        my_shop_brokerage: function (done) {
                            commission.getMyShopBrokerage(userId, function(error, result){
                                done(null, result)
                            })
                        },
                        team_brokerage: function (done) {
                            commission.getMyTeamBrokerage(userId, function(error, result){
                                done(null, result)
                            })
                        },
                        shared_shop_brokerage: function (done) {
                            commission.getShardShopBrokerage(userId, function(error, result){
                                done(null, result)
                            })
                        }
                    }, function (error, result) {
                        res.json(messageUtil.composeSucceededMessage(req, "数据计算成功", result, 1));
                    })
                });
            });

        });
    });
}
/*宝宝树四期 大使业绩统计的相关计算  pzs 20171031  end**/

/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 start */
// 结算历史明细
exports.getBalanceHistoryDetail = function (req, res) {
    var query = req.query;
    var token = req.params.token;
    var balanceId = req.params.balanceId;

    toolUtil.getUserByToken(token, function(error, result){

        if(!result){
            logger.debug("commission-controller.js--ambassadorPerformance():userId:"+req.params.token+"  msg:" + error.message)
            res.json(messageUtil.composeFailedMessage(req, "登录已过期，请重新登录", 0));
            return ;
        }

        var userId = result._id;

        async.series({
            // close_actuarial: function (done) {
            //     commission.getWaitCloseActuarial(userId, function(error, result){
            //         done(null, result)
            //     })
            // },
            // 小区订单
            community_brokerage: function (done) {
                commission.getMyCommunityBalanceHisBrokerage(userId, balanceId, function(error, result){
                    done(null, result)
                })
            },
            // 自购订单
            my_shop_brokerage: function (done) {
                commission.getMyShopBalanceHisBrokerage(userId, balanceId, function(error, result){
                    done(null, result)
                })
            },
            // 团队订单
            team_brokerage: function (done) {
                commission.getMyTeamBalanceHisBrokerage(userId, balanceId, function(error, result){
                    done(null, result)
                })
            },
            // 分享订单
            shared_shop_brokerage: function (done) {
                commission.getShardShopBalanceHisBrokerage(userId, balanceId, function(error, result){
                    done(null, result)
                })
            }
        }, function (error, result) {
            res.json(messageUtil.composeSucceededMessage(req, "数据计算成功", result, 1));
        })
    });
}

// 获取佣金订单一览数据
exports.getCommissionOrderList = function (req, res) {
    var query = req.query;
    var token = req.params.token;
    var ts = req.params.ts;
    var commType = req.params.commType;

    commission.getCommissionOrderListService(ts, token, commType, query, function (err, result) {
        if (err) {
            logger.error('Failed to getCommissionOrderListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
        }
    })
};

// 团队佣金订单一览
exports.getTeamCommissionOrderList = function (req, res) {
    var query = req.query;
    var token = req.params.token;
    var ts = req.params.ts;
    var commType = req.params.commType;

    commission.getTeamCommissionOrderListService(ts, token, commType, query, function (err, result) {
        if (err) {
            logger.error('Failed to getCommissionOrderListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
        }
    })
};

// 获取佣金订单详情
// exports.getCommissionOrderDetail = function (req, res) {
//     var query = req.query;
//     var token = req.params.token;
//     var orderId = req.params.orderId;
//
//     commission.getCommissionOrderDetailService(token, orderId, query, function (err, result) {
//         if (err) {
//             logger.error('Failed to getCommissionOrderDetailService...!' + err.message);
//             res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
//         } else {
//             res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
//         }
//     })
// };

// 获取结算历史一览数据
exports.getBalanceHistoryList = function (req, res) {
    var query = req.query;
    var token = req.params.token;
    var ts = req.params.ts;

    commission.getBalanceHistoryListService(ts, token, query, function (err, result) {
        if (err) {
            logger.error('Failed to getBalanceHistoryListService...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
        }
    })
};

// 获取结算历史订单一览数据
// exports.getBalanceHisOrderList = function (req, res) {
//     var query = req.query;
//     var token = req.params.token;
//     var ts = req.params.ts;
//     var balanceId = req.params.balanceId;
//     var balanceAmbUserId = req.params.balanceAmbUserId;
//
//     commission.getBalanceHisOrderListService(ts, token, balanceId, balanceAmbUserId, query, function (err, result) {
//         if (err) {
//             logger.error('Failed to getBalanceHisOrderListService...!' + err.message);
//             res.json(messageUtil.composeFailedMessage(req, err.message, 7021));
//         } else {
//             res.json(messageUtil.composeSucceededMessage(req, null, result, 7021));
//         }
//     })
// };
/* 宝宝树66小区 sprint6 小区大使业绩页面 新增结算历史明细和佣金订单一览页面 add wangcan 20171208 end */